package com.song.codesandbox.controller;

import com.song.codesandbox.JavaDockerCodeSandBox;
import com.song.codesandbox.JavaNativeCodeSandBox;
import com.song.codesandbox.model.ExecuteCodeRequest;
import com.song.codesandbox.model.ExecuteCodeResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/")
public class IndexController {

    private static final Logger log = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private JavaDockerCodeSandBox javaDockerCodeSandBox;

    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }

    @PostMapping("/execute")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        // 鉴权
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            // todo 可向响应中写入信息
            return null;
        }

        if (request == null) {
            throw new RuntimeException("请求参数为空");
        }

        ExecuteCodeResponse executeCodeResponse = javaDockerCodeSandBox.executeCode(executeCodeRequest);
        log.info("java代码接口响应结果:{}", response);

        return executeCodeResponse;
    }
}
